<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
      <el-form-item label="收费站" prop="deptId" v-if="deptId==101">
        <el-tree-select v-model="queryParams.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
          class="margin-right" placeholder="请选择部门" check-strictly clearable @change="bindChangeTree($event,'deptId')" />
      </el-form-item>
      <el-form-item label="公开时间" prop="openTime">
        <el-date-picker clearable v-model="queryParams.openTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择公开时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="标题" prop="topic">
        <el-input v-model="queryParams.topic" placeholder="请输入标题" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['coordination:business:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Menu" @click="handleStatistics">统计</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['coordination:business:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="businessList" @selection-change="handleSelectionChange" show-overflow-tooltip>
      <el-table-column type="index" width="65" align="center" label="序号" />
      <el-table-column label="收费站" align="center" prop="deptName" v-if="deptId==101" />
      <el-table-column label="公开时间" align="center" prop="openTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.openTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="topic" />
      <!-- <el-table-column label="公开内容" align="center" prop="content" /> -->
      <el-table-column label="附件" align="center" prop="attachment">
        <template #default="scope">
          <el-button @click.stop="previewFun(scope.row.attachment)" v-if="scope.row.attachment">查看</el-button>
          <span v-else>暂无数据</span>
        </template>
      </el-table-column>
      <el-table-column label="上传时间" align="center" prop="reportTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reportTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上传人" align="center" prop="reporterName" />
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleUpdate(scope.row,1)">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['coordination:business:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['coordination:business:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改企务公开对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="businessRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="收费站" prop="deptId">
          <el-tree-select style="width: 100%;" v-model="form.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }"
            value-key="id" class="margin-right" placeholder="请选择部门" check-strictly clearable :disabled="isShow" />
        </el-form-item>
        <el-form-item label="公开时间" prop="openTime">
          <el-date-picker clearable :disabled="isShow" style="width: 100%;" v-model="form.openTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择公开时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="标题" prop="topic">
          <el-input v-model="form.topic" placeholder="请输入标题" :disabled="isShow" />
        </el-form-item>
        <el-form-item label="公开内容">
          <el-input v-model="form.content" type="textarea" placeholder="请输入工作内容" rows="6" :disabled="isShow" />
        </el-form-item>
        <el-form-item label="附件" prop="attachment">
          <file-upload v-model="form.attachment" :disabled="isShow" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" rows="6" :disabled="isShow" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-if="!isShow">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <Viewer ref="fileViewerRef" :dialog-doc="dialogDoc" />

    <Statistics :echartsData="statisticsData" ref="statisticsRef" @changeType="handleStatistics" />

  </div>
</template>

<script setup name="Business">
import { listBusiness, getBusiness, delBusiness, addBusiness, updateBusiness, getStatistics } from "@/api/coordination/business";
import { deptTreeSelect } from "@/api/system/user";
import { getCKInfo } from '@/utils/auth'
import Viewer from "@/components/Custom/viewer.vue";
import Statistics from "./components/Statistics.vue";
import moment from "moment";
const { proxy } = getCurrentInstance();
const route = useRoute();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const businessList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptOptions = ref([])
const deptId = ref(Number(getCKInfo('deptId')))
const fileViewerRef = ref()
const dialogDoc = ref(false)
const type = ref()
const isShow = ref(false)
const statisticsType = ref(1)
const statisticsData = ref({ series: [{ data: [] }, { data: [] }], xaxis: [] })
const statisticsRef = ref()

if (route.query) {
  type.value = route.query.type;
}
const data = reactive({
  form: { deptId: deptId.value, type: type.value },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: deptId.value,
    openTime: null,
    topic: null,
    reportTime: null,
    reporter: null,
    type: type.value
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询企务公开列表 */
function getList() {
  loading.value = true;
  listBusiness(queryParams.value).then(response => {
    businessList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: deptId.value,
    openTime: null,
    topic: null,
    content: null,
    attachment: null,
    reportTime: null,
    reporter: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    type: type.value
  };
  proxy.resetForm("businessRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  isShow.value = false;
  open.value = true;
  title.value = "添加企务公开";
}

/** 修改按钮操作 */
function handleUpdate(row, type) {
  reset();
  const _id = row.id || ids.value
  getBusiness(_id).then(response => {
    form.value = response.data;
    open.value = true;

    if (type == 1) {
      isShow.value = true;
      title.value = "查看企务公开";
    } else {
      isShow.value = false;
      title.value = "修改企务公开";
    }
  });
}

function handleStatistics(date) {
  // 本年  本季度  本月
  // const startTime = moment(moment().quarter(moment().quarter()).startOf('quarter').valueOf()).format('YYYY-MM-DD');
  // const endTime = moment(moment().quarter(moment().quarter()).endOf('quarter').valueOf()).format('YYYY-MM-DD');
  // "startTime": statisticsType.value==1?moment().format('YYYY')+'-01-01': statisticsType.value==2?startTime: moment().format('YYYY-MM')+'-01',
  // "endTime": statisticsType.value==1?moment().format('YYYY')+'-12-31': statisticsType.value==2?endTime: moment().endOf('month').format('YYYY-MM-DD'),
  if (!date || !date.startDate) {
    date.startDate = moment().format('YYYY-MM') + '-01'
    date.endDate = moment().endOf('month').format('YYYY-MM-DD')
  }
  statisticsData.value.xaxis = []
  statisticsData.value.series[0].data = []
  getStatistics({
    "startTime": date.startDate,
    "endTime": date.endDate,
    "type": type.value
  }).then(res => {
    if (res.code == 200 && res.data) {
      res.data.forEach(item => {
        statisticsData.value.xaxis.push(item.deptName)
        statisticsData.value.series[0].data.push(item.openCount)
      })
      statisticsRef.value.open();
    }
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["businessRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBusiness(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBusiness(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除企务公开编号为"' + _ids + '"的数据项？').then(function () {
    return delBusiness(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('coordination/business/export', {
    ...queryParams.value
  }, `企务公开_${new Date().getTime()}.xlsx`)
}
// 预览
const previewFun = (file) => {
  dialogDoc.value = true;
  let data = {};

  // 上传过的文件组成完成的网络路径
  if (file && file.indexOf(',') == -1) {
    data.src = `${baseUrl}${file}`;
  } else if (file && file.indexOf(',') != -1) {
    let src = file.split(',');
    let srcArr = []
    src.forEach(item => { srcArr.push(`${baseUrl}${item}`) })
    data.src = srcArr.join(',');
    file = srcArr[0]
  }

  const arr = file.split(".");
  const suffix = arr[arr.length - 1];
  if (suffix == "docx" || suffix == "doc") {
    fileViewerRef.value?.viewDocx(data, '重点工作');
  } else if (suffix == "xlsx" || suffix == "xls") {
    fileViewerRef.value?.viewXlsx(data);
  } else if (suffix == "jpg" || suffix == "jpeg" || suffix == "png") {
    fileViewerRef.value?.viewImg(data);
  } else if (suffix == "pdf") {
    fileViewerRef.value?.viewPdf(data);
  }
};
getList();
getDeptTree()
</script>
